<template>
  <div>
    <DynamicTable
      :data-request="loadTableData"
      :columns="columns"
      :expanded-row-keys="expandedRowKeys"
      @expand="handleExpand"
    >
      <template #toolbar>
        <a-button type="primary" @click="openMenuModal({})"> <PlusOutlined />新增 </a-button>
        <a-button type="primary" @click="handleExpandAndClose()"
          ><SwapOutlined /> 展开/折叠
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="tsx" setup>
  import { ref, h } from 'vue';
  import { cloneDeep, uniq } from 'lodash-es';
  import {
    DeleteOutlined,
    EditOutlined,
    PlusOutlined,
    SwapOutlined,
    RightOutlined,
  } from '@ant-design/icons-vue';
  import { baseColumns, type TableListItem, type TableColumnItem } from './columns';
  import { useMenuSchemas } from './formSchemas';
  import type { TreeSelectProps } from 'ant-design-vue';
  import { getMenuList, updateMenu, createMenu, deleteMenu } from '@/api/system/menu';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/useFormModal';
  import { formatMenu2Tree } from '@/core/permission/utils';

  defineOptions({
    name: 'SysMenu',
  });

  const menuList=ref([]);
  const menuTree = ref<TreeSelectProps['treeData']>([]);
  const [DynamicTable, dynamicTableInstance] = useTable({
    pagination: false,
    size: 'small',
    rowKey: 'menuId',
    bordered: true
  });
  const [showModal] = useFormModal();

  const hasExpandKeys = ref<string[]>([]);
  const expandedRowKeys = ref<string[]>([]);
  const handleExpandAndClose = () => {
    if (expandedRowKeys.value.length) {
      expandedRowKeys.value = [];
    } else {
      expandedRowKeys.value = hasExpandKeys.value.map((i) => i);
    }
  };
  const handleExpand = (expanded, record) => {
    if (expanded) {
      expandedRowKeys.value.push(record.menuId);
    } else {
      const _index = expandedRowKeys.value.findIndex((item) => item == record.menuId);
      expandedRowKeys.value.splice(_index, 1);
    }
  };

  const loadTableData = async (params) => {
    const data = await getMenuList(params);
    menuList.value=data.result;
    hasExpandKeys.value = uniq(
      data.result
        .filter((item) => item.parentId && item.parentId != '0')
        .map((item) => item.parentId),
    );
    menuTree.value = formatMenu2Tree(cloneDeep(data.result), '0');
    return { list: formatMenu2Tree(cloneDeep(data.result), '0') };
  };

  const openMenuModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.menuId ? '编辑' : '新增'}菜单`,
        width: 700,
        onFinish: async (values) => {
          
          record.menuId && (values.menuId = record.menuId);
          const parentTree = menuList.value.find(item => item.menuId === values.parentId);
          console.log(parentTree, "111111111111");
          if(parentTree==undefined){
            values["perms"]="P";
          }
          else{
            values["perms"]=parentTree.perms;
          }
          console.log('新增/编辑菜单', values);
          // if (values.menuType === 'C' && values.component?.length) {
          //   values.component = values.component.join('/');
          //   values.component = values.component.split('.')[0]
          // }
          await (record.menuId ? updateMenu : createMenu)(values);
          dynamicTableInstance.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: useMenuSchemas(),
      },
    });

    formRef?.updateSchema([
      {
        field: 'parentId',
        componentProps: {
          treeDefaultExpandedKeys: ['0'].concat(record?.keyPath || []),
          treeData: ref([{ menuId: '0', menuName: '主目录', children: menuTree.value }]),
        },
      },
    ]);

    formRef?.setFieldsValue({
      ...record,
      icon: record.icon ?? '',
      //component: record.component?.split('/') || [],
      parentId: record.parentId ?? '0',
    });
  };
  const delRowConfirm = async (record: TableListItem) => {
    await deleteMenu({ menuId: record.menuId });
    dynamicTableInstance.reload();
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 220,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      actions: ({ record }) => [
        {
          label: '编辑',
          icon: h(EditOutlined),
          onClick: () => openMenuModal(record),
        },
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script>
